const { get, run, all } = require('../config/db');

class Protocol {
  // 创建协议
  static async create(name, description, userId, categoryId = null, isPublic = false) {
    try {
      const result = await run(
        'INSERT INTO protocols (name, description, user_id, category_id, is_public) VALUES (?, ?, ?, ?, ?)',
        [name, description, userId, categoryId, isPublic ? 1 : 0]
      );
      
      return { 
        id: result.id, 
        name, 
        description, 
        userId, 
        categoryId, 
        isPublic 
      };
    } catch (error) {
      console.error('创建协议失败:', error);
      throw error;
    }
  }
  
  // 获取用户的所有协议
  static async findByUserId(userId) {
    try {
      const rows = await all(
        `SELECT p.*, c.name as category_name 
         FROM protocols p 
         LEFT JOIN protocol_categories c ON p.category_id = c.id 
         WHERE p.user_id = ? OR p.is_public = 1 
         ORDER BY p.name`,
        [userId]
      );
      
      return rows;
    } catch (error) {
      console.error('获取协议失败:', error);
      throw error;
    }
  }
  
  // 获取分类下的所有协议
  static async findByCategoryId(categoryId, userId) {
    try {
      const rows = await all(
        `SELECT p.*, c.name as category_name 
         FROM protocols p 
         LEFT JOIN protocol_categories c ON p.category_id = c.id 
         WHERE p.category_id = ? AND (p.user_id = ? OR p.is_public = 1) 
         ORDER BY p.name`,
        [categoryId, userId]
      );
      
      return rows;
    } catch (error) {
      console.error('获取协议失败:', error);
      throw error;
    }
  }
  
  // 通过ID查找协议
  static async findById(id, userId) {
    try {
      const protocol = await get(
        `SELECT p.*, c.name as category_name 
         FROM protocols p 
         LEFT JOIN protocol_categories c ON p.category_id = c.id 
         WHERE p.id = ? AND (p.user_id = ? OR p.is_public = 1)`,
        [id, userId]
      );
      
      return protocol || null;
    } catch (error) {
      console.error('查找协议失败:', error);
      throw error;
    }
  }
  
  // 更新协议
  static async update(id, name, description, categoryId, isPublic) {
    try {
      await run(
        'UPDATE protocols SET name = ?, description = ?, category_id = ?, is_public = ? WHERE id = ?',
        [name, description, categoryId, isPublic ? 1 : 0, id]
      );
      
      return { id, name, description, categoryId, isPublic };
    } catch (error) {
      console.error('更新协议失败:', error);
      throw error;
    }
  }
  
  // 删除协议
  static async delete(id) {
    try {
      await run(
        'DELETE FROM protocols WHERE id = ?',
        [id]
      );
      
      return true;
    } catch (error) {
      console.error('删除协议失败:', error);
      throw error;
    }
  }
  
  // 获取协议的所有元素
  static async getElements(protocolId) {
    try {
      const rows = await all(
        `SELECT pe.*, 
                fep.value, 
                nep.data_type, 
                aep.calc_type
         FROM protocol_elements pe
         LEFT JOIN fixed_element_properties fep ON pe.id = fep.element_id
         LEFT JOIN normal_element_properties nep ON pe.id = nep.element_id
         LEFT JOIN auto_element_properties aep ON pe.id = aep.element_id
         WHERE pe.protocol_id = ?
         ORDER BY pe.position`,
        [protocolId]
      );
      
      return rows;
    } catch (error) {
      console.error('获取协议元素失败:', error);
      throw error;
    }
  }
}

module.exports = Protocol;
